<template>
  <a-card class="a-card">
    <h2>登录</h2>
    <a-form
    id="components-form-demo-normal-login"
    :form="form"
    class="login-form"
    @submit="handleSubmit">
      <a-form-item>
      <a-input
        v-decorator="[
          'userName',
          { rules: [{ required: true, message: 'Please input your username!' }] }
        ]"
        placeholder="账号">
        <a-icon
          slot="prefix"
          type="user"
          style="color: rgba(0,0,0,.25)"
        />
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-input
        v-decorator="[
          'password',
          { rules: [{ required: true, message: 'Please input your Password!' }] }
        ]"
        type="password"
        placeholder="密码"
      >
        <a-icon
          slot="prefix"
          type="lock"
          style="color: rgba(0,0,0,.25)"
        />
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-checkbox
        v-decorator="[
          'remember',
          {
            valuePropName: 'checked',
            initialValue: true,
          }
        ]"
      >
        记住密码
      </a-checkbox>
      <a
        class="login-form-forgot"
        href=""
      >
        忘记密码
      </a>
      <a-button
        type="primary"
        html-type="submit"
        class="login-form-button"
      >
        登录
      </a-button>
    </a-form-item>
  </a-form>
  </a-card>
</template>

<script>
export default {
  data () {
    return {
      loginInfo: {
        username: '',
        password: ''
      }
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  methods: {
    handleSubmit (e) {
      localStorage.removeItem('user')
      e.preventDefault()
      this.form.validateFields(async (err, values) => {
        if (err) return this.$message.info('验证失败，请重试')
        if (!err) {
          this.loginInfo.username = values.userName
          this.loginInfo.password = values.password
          let res = await this.$http.post(`login`, this.loginInfo)
          if (res.data.meta.status !== 200) {
            return this.$message.info(res.data.meta.msg)
          } else if (res.data.meta.status === 200) {
            this.$message.info(res.data.meta.msg)
            localStorage.setItem('user', this.loginInfo.username)
            sessionStorage.setItem('token', res.data.data.token)
            this.$router.push('/welcome')
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.a-card {
  position: absolute;
  width: 500px;
  height: 300px;
  top: 50%;
  left: 50%;
  transform: translate(-50% ,-65%);
  background-color: #eee;
  box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.25);
}
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
</style>
